package icu.gking.cart_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import icu.gking.cart_system.common.Result;
import icu.gking.cart_system.pojo.*;
import icu.gking.cart_system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailsService orderDetailsService;

    @Autowired
    private CartService cartService;

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private UserService userService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    @Transactional
    public Result<Map<String, Object>> createOrder(@RequestBody Map<String, Integer> params) {
        try {
            Integer userId = params.get("userId");
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            // 获取用户购物车有效商品
            QueryWrapper<Cart> cartQuery = new QueryWrapper<>();
            cartQuery.eq("user_id", userId);
            List<Cart> cartItems = cartService.list(cartQuery);
            
            if (cartItems.isEmpty()) {
                return Result.error("购物车为空");
            }

            // 按卖家分组有效商品
            Map<Integer, List<Cart>> sellerItemsMap = new HashMap<>();
            for (Cart item : cartItems) {
                Commodity commodity = commodityService.getById(item.getCommodityId());
                // 检查商品是否有效
                if (commodity == null || commodity.getStatus() != 1 || commodity.getStock() < item.getAmount()) {
                    continue; // 跳过无效商品
                }
                
                sellerItemsMap.computeIfAbsent(commodity.getSellerId(), k -> new ArrayList<>())
                        .add(item);
            }

            // 如果没有有效商品，返回错误
            if (sellerItemsMap.isEmpty()) {
                return Result.error("没有可提交的有效商品");
            }

            // 创建订单
            List<Orders> createdOrders = new ArrayList<>();
            for (Map.Entry<Integer, List<Cart>> entry : sellerItemsMap.entrySet()) {
                List<Cart> items = entry.getValue();
                
                // 计算订单总金额
                double totalMoney = items.stream()
                        .mapToDouble(item -> item.getPrice() * item.getAmount())
                        .sum();

                // 创建订单
                Orders order = new Orders();
                order.setUserId(userId);
                order.setTotalMoney(totalMoney);
                order.setStatus(1); // 待处理
                order.setOrderTime(new Date());
                order.setUpdateTime(new Date());
                
                ordersService.save(order);
                createdOrders.add(order);

                // 创建订单详情并更新库存
                for (Cart item : items) {
                    // 再次检查商品状态和库存
                    Commodity commodity = commodityService.getById(item.getCommodityId());
                    if (commodity == null || commodity.getStatus() != 1 || commodity.getStock() < item.getAmount()) {
                        throw new RuntimeException("商品 " + item.getCommodityName() + " 状态已改变，请重新确认");
                    }

                    OrderDetails detail = new OrderDetails();
                    detail.setOrderId(order.getOrderId());
                    detail.setCommodityId(item.getCommodityId());
                    detail.setCommodityName(item.getCommodityName());
                    detail.setPrice(item.getPrice());
                    detail.setAmount(item.getAmount());
                    detail.setMoney(item.getMoney());
                    detail.setCreateTime(new Date());
                    
                    orderDetailsService.save(detail);

                    // 更新商品库存
                    commodity.setStock(commodity.getStock() - item.getAmount());
                    commodityService.updateById(commodity);

                    // 从购物车中删除已下单的商品
                    cartService.removeById(item.getCartId());
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("orders", createdOrders);
            return Result.success(result);

        } catch (Exception e) {
            log.error("创建订单失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 确保事务回滚
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户订单列表
     */
    @GetMapping("/list/{userId}")
    public Result<List<Orders>> getUserOrders(@PathVariable Integer userId) {
        try {
            QueryWrapper<Orders> orderQuery = new QueryWrapper<>();
            orderQuery.eq("user_id", userId)
                     .orderByDesc("order_time");
            
            List<Orders> orders = ordersService.list(orderQuery);
            return Result.success(orders);
        } catch (Exception e) {
            log.error("获取用户订单列表失败 - userId: {}", userId, e);
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/details/{orderId}")
    public Result<List<OrderDetails>> getOrderDetails(@PathVariable Integer orderId) {
        try {
            QueryWrapper<OrderDetails> detailQuery = new QueryWrapper<>();
            detailQuery.eq("order_id", orderId);
            List<OrderDetails> details = orderDetailsService.list(detailQuery);
            return Result.success(details);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return Result.error("获取订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/update/status")
    @Transactional
    public Result<Boolean> updateOrderStatus(@RequestBody Map<String, Integer> params) {
        try {
            Integer orderId = params.get("orderId");
            Integer status = params.get("status");

            if (orderId == null || status == null) {
                return Result.error("参数不完整");
            }

            Orders order = ordersService.getById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }

            order.setStatus(status);
            order.setUpdateTime(new Date());
            
            // 如果订单被拒绝，恢复商品库存
            if (status == 3) {
                QueryWrapper<OrderDetails> detailQuery = new QueryWrapper<>();
                detailQuery.eq("order_id", orderId);
                List<OrderDetails> details = orderDetailsService.list(detailQuery);
                
                for (OrderDetails detail : details) {
                    Commodity commodity = commodityService.getById(detail.getCommodityId());
                    if (commodity != null) {
                        commodity.setStock(commodity.getStock() + detail.getAmount());
                        commodityService.updateById(commodity);
                    }
                }
            }

            return Result.success(ordersService.updateById(order));
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return Result.error("更新订单状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取商家的订单列表
     */
    @GetMapping("/seller/{sellerId}")
    public Result<List<Map<String, Object>>> getSellerOrders(@PathVariable Integer sellerId) {
        try {
            // 先获取该卖家的所有商品ID
            QueryWrapper<Commodity> commodityQuery = new QueryWrapper<>();
            commodityQuery.eq("seller_id", sellerId);
            List<Commodity> sellerCommodities = commodityService.list(commodityQuery);
            Set<Integer> commodityIds = sellerCommodities.stream()
                    .map(Commodity::getCommodityId)
                    .collect(Collectors.toSet());

            // 通过商品ID找到相关的订单详情
            if (!commodityIds.isEmpty()) {
                QueryWrapper<OrderDetails> detailQuery = new QueryWrapper<>();
                detailQuery.in("commodity_id", commodityIds);
                List<OrderDetails> orderDetails = orderDetailsService.list(detailQuery);
                
                // 获取相关的订单ID
                Set<Integer> orderIds = orderDetails.stream()
                        .map(OrderDetails::getOrderId)
                        .collect(Collectors.toSet());

                if (!orderIds.isEmpty()) {
                    // 获取订单信息
                    QueryWrapper<Orders> orderQuery = new QueryWrapper<>();
                    orderQuery.in("order_id", orderIds)
                            .orderByDesc("order_time");
                    List<Orders> orders = ordersService.list(orderQuery);
                    
                    // 组装返回数据
                    List<Map<String, Object>> result = new ArrayList<>();
                    for (Orders order : orders) {
                        User buyer = (User) userService.getById(order.getUserId());
                        
                        Map<String, Object> orderMap = new HashMap<>();
                        orderMap.put("orderId", order.getOrderId());
                        orderMap.put("buyerId", order.getUserId());
                        orderMap.put("buyerName", buyer != null ? buyer.getUserName() : "未知用户");
                        orderMap.put("orderTime", order.getOrderTime());
                        orderMap.put("status", order.getStatus());
                        orderMap.put("totalMoney", order.getTotalMoney());
                        
                        result.add(orderMap);
                    }
                    
                    return Result.success(result);
                }
            }
            
            // 如果没有找到订单，返回空列表
            return Result.success(new ArrayList<>());
        } catch (Exception e) {
            log.error("获取商家订单列表失败 - sellerId: {}", sellerId, e);
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }
} 